// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

Vue.config.productionTip = false

/* eslint-disable no-new */

var menuData = [];

//自定义权限指令
Vue.directive('has', {
  bind: function (el, binding, vnode) {
    var perms = binding.value;
    // 获取按钮权限
    if (!Vue.prototype.$_has(perms)) {
      el.style.display = "none"
    }
  }
});
// 权限检查方法
Vue.prototype.$_has = function (perm) {
  var isExist = false;
  var menus = menuData;
  if (!menus) {
    return false;
  }
  isExist = hasPerms(menus, perm)
  return isExist;
};


var hasPerms = function (menus, perm) {
  for (var i in menus) {
    var m = menus[i];
    if (m.perms && m.perms == perm) {
      return true;
    }
    var chilren = m.children;
    var has = hasPerms(chilren, perm);
    if (has) {
      return true;
    }
  }
  return false;
}


router.beforeEach((to, from, next) => {
    if (to.path == "/" || to.path == "/nopermission") {
      next();
      return;
    }

    if (to.path == "/home") {
      if (sessionStorage.getItem("user")) {
        next();
        return;
      }
    }
    var menus = menuData;
    if (!menus) {
      next("/");
      return;
    }
    if (hasUrlPerms(menus, to.path)) {
      next();
    } else {
      next("/nopermission")
    }
  }
)

var hasUrlPerms = function (menus, path) {
  if (menus && menus instanceof Array) {
    for (var i in menus) {
      var m = menus[i];
      if (m.url && m.url == path) {
        return true;
      }
      var chilren = m.children;
      var has = hasUrlPerms(chilren, path);
      if (has) {
        return true;
      }
    }
  }
  return false;
}
export {
  menuData
}
new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>'
})
